package leetcode.median;

import java.util.LinkedList;
import java.util.List;

import jdk.internal.vm.annotation.DontInline;

public class $54_SpiralOrder {
    public List<Integer> spiralOrder(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        int size = row * col;
        List<Integer> res = new LinkedList<>();

        int i = 0;
        int left = 0;
        int down = row - 1;
        int up = 0;
        int right = col - 1;
        while (left <= right && up <= down) {
            if (i == size) {
                break;
            }
            // 从左到右
            for (int j = left;j <= right;j++) {
                res.add(matrix[up][j]);
                i++;
            }

            if (i == size) {
                break;
            }
            // 从上到下
            for (int j = up + 1;j <= down;j++) {
                res.add(matrix[j][right]);
                i++;
            }

            if (i == size) {
                break;
            }
            // 从右到左
            for (int j = right - 1; j >= left;j--) {
                res.add(matrix[down][j]);
                i++;
            }

            if (i == size) {
                break;
            }
            for (int j = down - 1; j > up;j--) {
                res.add(matrix[j][left]);
                i++;
            }
            right--;
            up++;
            down--;
            left++;
        }
        return res;
    }
}
